//
//  AppDelegate.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/8/16.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "AppDelegate.h"
#import "LSHomeViewController.h"
#import "ViewController.h"
#import "ZKTransitionTestDemoVC.h"
#import "KZListenSpeakVocabularyImporveVC.h"
#import "KZPronounceImproveVC.h"
#import "KZUnfamiliarVocabularyImproveVC.h"
#import "LSTestWrongQuesViewController.h"
#import "LSSystemConfig.h"
#import "LSNewHomeViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    printf("11");
    [self listenNetStatus];
    // Override point for customization after application launch.
    //开启bug监测
    [self setupBugly];
    [self initKouYuEngine];
    [self scrollAppearanceFit];
    
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //KUserDefaults(@"http://172.16.41.236:2048/",@"SystemIP");

    [self enterApp];
    
    return YES;
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
     return UIInterfaceOrientationMaskPortrait;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationWillResignActive" object:nil];
}
- (void)listenNetStatus {
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [NSUserDefaults.standardUserDefaults setObject:@(YES) forKey:@"KZNetValid"];
                NSLog(@"切换到WIFI网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [NSUserDefaults.standardUserDefaults setObject:@(YES) forKey:@"KZNetValid"];
                NSLog(@"切换到3/4G网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [NSUserDefaults.standardUserDefaults setObject:@(false) forKey:@"KZNetValid"];
                NSLog(@"网络连接异常");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD showText:@"请检查网络" state:KZHUDStateModeFailure duration:5];

                });
                [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationWillResignActive" object:nil];

                break;
            case AFNetworkReachabilityStatusUnknown:
                [NSUserDefaults.standardUserDefaults setObject:@(false) forKey:@"KZNetValid"];

                NSLog(@"未知网络");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD showText:@"请检查网络" state:KZHUDStateModeFailure duration:5];
                    
                });
                [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationWillResignActive" object:nil];
                break;
            default:
                break;
        }
    }];
    [manager startMonitoring];
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
     [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationWillEnterForeground" object:nil];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {

    NSString *old_userID = KGetUserDefaults(LG_Old_UserID);
    NSString *old_serverUrl = KGetUserDefaults(LG_Old_ServerUrl);
    NSString *addressString = [AddressOperater getBaseAddress];
    NSInteger state = [[[Authentication alloc] init] getUserTokenState];//判断是否在线
    if ([old_serverUrl isEqualToString:addressString]) {
        if (state==1) {//token有效
            if([DR_UserInfo.UserID isEqualToString:old_userID]) {
                if ([self isLoginNavRoot]) {
                    NSLog(@"在登录界面，重新登录。。。");
                    [self setupLoginViewController];
                } else {
                    NSLog(@"恢复活跃。。。");
                }
            } else {
                NSLog(@"切换了账号");
                [self setupLoginViewController];
            }
        } else {
            //token失效，登出
            NSLog(@"token失效");
        }
        
    } else {
        //切换了服务器地址
        NSLog(@"切换了服务器地址");
        [self setupLoginViewController];
    }
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark - 进入系统
- (void)enterApp {
    
    NSInteger state = [[[Authentication alloc] init] getUserTokenState];//判断是否在线
    if (state==1) {
        //已登录
        KUserDefaults(@"1", BKIsLogin);
        [self getSystemIP];
        [self getImgIP];
        [self getTestLayerWithInfo:[[[Authentication alloc]init] userInfofromCheyChain]];

       // LSHomeViewController *home = [[LSHomeViewController alloc] init];
        LSNewHomeViewController *home = [[LSNewHomeViewController alloc] init];
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:home];
        self.window.rootViewController = navigationController;
        
    } else {
        
        KUserDefaults(@"0", BKIsLogin);
        [self setupLoginViewController];
    }
}

#pragma mark - 启动登录界面
- (void)setupLoginViewController {
    Authentication *auth = [[Authentication alloc] init];
    [auth loginWithSystemID:@"101" titleName:@"听说智能训练" success:^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //存储本次账号和地址
            NSString *addressString = [AddressOperater getBaseAddress];
            KUserDefaults(addressString, LG_Old_ServerUrl);
            NSString *userID = DR_UserInfo.UserID;
            KUserDefaults(userID, LG_Old_UserID);
            //本次登录成功
            KUserDefaults(@"1", BKIsLogin);
            dispatch_async(dispatch_get_main_queue(), ^{
                //在主线程中执行
                [self getSystemIP];
                [self getImgIP];
                [self getTestLayerWithInfo:[[[Authentication alloc]init] userInfofromCheyChain]];
                
                //LSHomeViewController *home = [[LSHomeViewController alloc] init];
                LSNewHomeViewController *home = [[LSNewHomeViewController alloc] init];
                UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:home];
                self.window.rootViewController = navigationController;
                
            });
        });
    }];
}


@end
